const Assessment = require('../models/Assessment');
const Result = require('../models/Result');
const path = require('path');
const fs = require('fs');

const assessmentService = {
  // 创建新测评（心理测评）
  async createAssessment(assessmentData) {
    const { title, description, duration } = assessmentData;
    
    // 验证必填字段
    if (!title || !duration) {
      throw new Error('标题和时长是必填项');
    }
    
    const assessmentId = await Assessment.create({ title, description, duration });
    return { assessmentId };
  },

  // 获取所有测评（从题库文件中读取）
  async getAllAssessments() {
    try {
      const questionBankDir = path.join(__dirname, '../question_bank');
      const files = fs.readdirSync(questionBankDir).filter(file => file.endsWith('.json'));
      
      const assessments = files.map((file, index) => {
        const filePath = path.join(questionBankDir, file);
        const fileContent = fs.readFileSync(filePath, 'utf8');
        const questions = JSON.parse(fileContent);
        
        // 从文件名中提取标题（移除.json后缀）
        const title = file.replace('.json', '');
        
        return {
          id: index + 1, // 使用索引作为临时ID
          title: title,
          description: `包含${questions.length}个问题的${title}`,
          duration: Math.ceil(questions.length / 2), // 假设每个问题需要30秒，向上取整为分钟
          questionCount: questions.length
        };
      });
      
      return assessments;
    } catch (error) {
      console.error('读取题库文件失败:', error);
      // 如果读取失败，返回默认的测评列表
      return [
        {
          id: 1,
          title: '中学生心理健康量表',
          description: '评估中学生心理健康状况，包括考试焦虑、学业压力等多个维度',
          duration: 30,
          questionCount: 60
        },
        {
          id: 2,
          title: '心理测试题库',
          description: '全面的心理健康测评，包括焦虑、抑郁等常见心理问题评估',
          duration: 20,
          questionCount: 50
        }
      ];
    }
  },

  // 获取测评详情
  async getAssessmentById(id) {
    try {
      const questionBankDir = path.join(__dirname, '../question_bank');
      const files = fs.readdirSync(questionBankDir).filter(file => file.endsWith('.json'));
      
      // 将ID转换为数字
      const assessmentId = parseInt(id);
      
      // 检查ID是否在有效范围内
      if (assessmentId >= 1 && assessmentId <= files.length) {
        const file = files[assessmentId - 1]; // 索引从0开始
        const filePath = path.join(questionBankDir, file);
        const fileContent = fs.readFileSync(filePath, 'utf8');
        const questions = JSON.parse(fileContent);
        
        // 从文件名中提取标题（移除.json后缀）
        const title = file.replace('.json', '');
        
        return {
          id: assessmentId,
          title: title,
          description: `包含${questions.length}个问题的${title}`,
          duration: Math.ceil(questions.length / 2),
          questionCount: questions.length
        };
      } else {
        throw new Error('测评不存在');
      }
    } catch (error) {
      console.error('读取测评详情失败:', error);
      throw new Error('测评不存在');
    }
  }
};

module.exports = assessmentService;